package logic.algorithm;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;


import datamodel.Grid;
/**
 * 
 */
import datamodel.GridElement;

/**
 * @author Toa, Michelle, Steffen
 * @version 0.1
 *
 */
public class Moore implements Algorithm {

	boolean solved = false;
	Grid grid;
	/** marks the start of the way */
	GridElement start;
	/** queue for storing the waypoints */
	Queue<GridElement> queue;
	
	/* (non-Javadoc)
	 * @see logic.algorithm.Algorithm#init(datamodel.Grid)
	 */ 
	@Override
	public void init(Grid grid) {
		//init grid
		this.grid = grid;
		//create queue
		queue = new LinkedList<GridElement>();
		//get start element
		start = grid.getStartElement();
		//set distance from start to 0 
		start.setDistance(0);
		//add start to queue
		queue.offer(start);
	}

	/* (non-Javadoc)
	 * @see logic.algorithm.Algorithm#doNextStep()
	 */
	@Override
	public boolean doNextStep() {
		
		//queue is empty -> way solved (return false in order to stop iterations) 
		//if(queue.size() == 0)
		if(queue.isEmpty())
		{	
			solved = true;
			return false;
		}
		//get head and remove it 
		GridElement current = queue.poll();
		
		//detect all neighbors of the current node
		Vector<GridElement> neighbors = grid.getNeighborsFrom(current, false).getNeighbors();
		
		for(GridElement element: neighbors){
			
			if(element.getDistance() == -1 && 
					element.getState().getWayCost() != Integer.MAX_VALUE){
				
				element.setDistance(current.getDistance() + 4);
				queue.offer(element);
				//for path
				element.setPrecursor(current);
			}
		}
		
		return true;
	}

	/* (non-Javadoc)
	 * @see logic.algorithm.Algorithm#isSolved()
	 */
	@Override
	public boolean isSolved() {
		return solved;
	}

}
